package com.szholly.pro.watergas_server.ps.android.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.szholly.utils.util.JSONUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class NonNullUtil {

	public static String toString(Object object) {
		return toString(object, "");
	}

	public static String toString(Object object, String defaultValue) {
		if (object == null) {
			return defaultValue;
		}
		if (object instanceof String) {
			return (String) object;
		}
		return object.toString();
	}

	public static JSONArray toJson(@SuppressWarnings("rawtypes") List list) {
		if (list == null || list.size() == 0) {
			return new JSONArray();
		} else {
			return JSONUtils.toJSONArray(list);
		}
	}

	public static JSONArray toJson(JSONArray array) {
		if (array == null) {
			return new JSONArray();
		} else {
			return array;
		}
	}

	public static <T> List<T> toList(List<T> list) {
		if (list == null) {
			return new ArrayList<T>();
		} else {
			return list;
		}
	}

	public static <K, V> Map<K, V> toMap(Map<K, V> map) {
		if (map == null) {
			return new HashMap<>();
		} else {
			return map;
		}
	}

	@SuppressWarnings("rawtypes")
	public static void put(JSONObject json, String key, Map value) {
		if (key == null) {
			return;
		}

		if (value == null) {
			json.put(key, new JSONObject());
		} else {
			json.put(key, JSONObject.fromObject(value));
		}
	}

	public static void put(JSONObject json, String key, JSONObject value) {
		if (key == null) {
			return;
		}

		if (value == null) {
			json.put(key, new JSONObject());
		} else {
			json.put(key, value);
		}
	}

	public static void put(JSONObject json, String key, JSONArray value) {
		if (key == null) {
			return;
		}
		json.put(key, toJson(value));
	}

	public static void put(JSONObject json, String key, @SuppressWarnings("rawtypes") List value) {
		if (key == null) {
			return;
		}
		json.put(key, toJson(value));
	}

}
